import { Card, Table, Row, Col, Statistic, Tag, Space, Modal, Button, Checkbox, Typography } from '@/utils/antd-imports';
import React from 'react';












const { Text } = Typography;

export const RiskTab = ({ subProjectsData = [] }) => {
  // 状态管理筛选条件
  const [filters, setFilters] = React.useState({
    showOverdue: true,
    showHighCost: true,
    showHighHour: true,
    showLowPayment: true,
  });

  // 计算风险页签的统计数据
  const calculateRiskStats = () => {
    // 逾期项目：预计结束时间已过但未完成的项目
    const overdueProjects = subProjectsData.filter(p => {
      if (!p?.expectedEndDate) return false;
      try {
        const endDate = new Date(p.expectedEndDate.replace(/\./g, '-'));
        const today = new Date();
        return endDate < today && p?.status !== '已回款';
      } catch (e) {
        return false;
      }
    }).length;
    
    // 高成本项目：成本率超过90%
    const highCostProjects = subProjectsData.filter(p => (p?.costRate || 0) > 0.9).length;
    
    // 高工时项目：工时超过预算120%
    const highHourProjects = subProjectsData.filter(p => {
      const budgetHours = p?.budgetHours || 0;
      const actualHours = p?.actualHours || 0;
      return budgetHours > 0 && (actualHours / budgetHours) > 1.2;
    }).length;
    
    // 低回款项目：回款比例低于50%
    const lowPaymentProjects = subProjectsData.filter(p => {
      const budgetAmount = p?.budgetAmount || 0;
      const paidAmount = p?.paidAmount || 0;
      return budgetAmount > 0 && (paidAmount / budgetAmount) < 0.5;
    }).length;
    
    // 按项目类型统计
    const projectTypeStats = {
      fullPackage: subProjectsData.filter(p => p?.projectType === '整包项目').length,
      manpower: subProjectsData.filter(p => p?.projectType === '人力项目').length,
      subcontract: subProjectsData.filter(p => p?.projectType === '分包项目').length
    };
    
    return {
      overdueProjects,
      highCostProjects,
      highHourProjects,
      lowPaymentProjects,
      projectTypeStats
    };
  };

  const riskStats = calculateRiskStats();

  // 显示合同内容的对话框
  const [contractVisible, setContractVisible] = React.useState(false);
  const [currentContract, setCurrentContract] = React.useState('');

  const showContract = (contractContent) => {
    setCurrentContract(contractContent);
    setContractVisible(true);
  };

  // 处理筛选条件变化
  const handleFilterChange = (changedValues) => {
    setFilters({ ...filters, ...changedValues });
  };

  // 获取筛选后的数据
  const getFilteredData = () => {
    return subProjectsData.filter(p => {
      const isOverdue = p?.expectedEndDate && new Date(p.expectedEndDate.replace(/\./g, '-')) < new Date() && p?.status !== '已回款';
      const isHighCost = (p?.costRate || 0) > 0.9;
      const isHighHour = (p?.budgetHours || 0) > 0 && ((p?.actualHours || 0) / p?.budgetHours) > 1.2;
      const isLowPayment = (p?.budgetAmount || 0) > 0 && ((p?.paidAmount || 0) / p?.budgetAmount) < 0.5;
      
      return (
        (filters.showOverdue && isOverdue) ||
        (filters.showHighCost && isHighCost) ||
        (filters.showHighHour && isHighHour) ||
        (filters.showLowPayment && isLowPayment)
      );
    });
  };

  // 子项目表格列定义
  const columns = [
    {
      title: '项目ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      render: (id) => <Text strong>{id}</Text>
    },
    {
      title: '子项目名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
      render: (text) => <Text strong>{text}</Text>
    },
    {
      title: '项目类型',
      dataIndex: 'projectType',
      key: 'projectType',
      width: 100,
      render: (type) => (
        <Tag color={getProjectTypeColor(type)}>
          {type}
        </Tag>
      )
    },
    {
      title: '客户名称',
      dataIndex: 'clientName',
      key: 'clientName',
      width: 150
    },
    {
      title: '对接人',
      dataIndex: 'contactPerson',
      key: 'contactPerson',
      width: 100
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 100
    },
    {
      title: '科室',
      dataIndex: 'division',
      key: 'division',
      width: 100
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {status}
        </Tag>
      )
    },
    {
      title: '合同号',
      dataIndex: 'contractNumber',
      key: 'contractNumber',
      width: 120,
      render: (text, record) => (
        <Text 
          underline 
          style={{cursor: 'pointer'}} 
          onClick={() => showContract(record.contractContent || '无合同内容')}
        >
          {text}
        </Text>
      )
    },
    {
      title: '预算金额',
      dataIndex: 'budgetAmount',
      key: 'budgetAmount',
      width: 120,
      render: (amount) => <Text>¥{(amount || 0).toLocaleString()}</Text>
    },
    {
      title: '已回款',
      dataIndex: 'paidAmount',
      key: 'paidAmount',
      width: 120,
      render: (amount) => <Text>¥{(amount || 0).toLocaleString()}</Text>
    },
    {
      title: '成本率',
      dataIndex: 'costRate',
      key: 'costRate',
      width: 100,
      render: (rate) => (
        <Text type={rate > 0.9 ? 'danger' : rate > 0.7 ? 'warning' : 'success'}>
          {(rate * 100).toFixed(2)}%
        </Text>
      )
    },
    {
      title: '时价',
      dataIndex: 'hourlyRate',
      key: 'hourlyRate',
      width: 100,
      render: (rate) => <Text>¥{rate || 0}</Text>
    },
    {
      title: '预算工时',
      dataIndex: 'budgetHours',
      key: 'budgetHours',
      width: 100,
      render: (hours) => <Text>{hours || 0}h</Text>
    },
    {
      title: '实际工时',
      dataIndex: 'actualHours',
      key: 'actualHours',
      width: 100,
      render: (hours) => <Text>{hours || 0}h</Text>
    },
    {
      title: '预计结束时间',
      dataIndex: 'expectedEndDate',
      key: 'expectedEndDate',
      width: 120
    },
    {
      title: '实际结束时间',
      dataIndex: 'actualEndDate',
      key: 'actualEndDate',
      width: 120
    }
  ];

  return (
    <>
      <div style={{ overflowX: 'auto', marginBottom: 24 }}>
        <div style={{ display: 'flex', minWidth: 'max-content' }}>
          <div style={{ minWidth: '150px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic 
                title="逾期项目" 
                value={riskStats.overdueProjects} 
                precision={0}
                valueStyle={{ color: riskStats.overdueProjects > 0 ? '#cf1322' : '#3f8600', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '150px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic 
                title="高成本项目" 
                value={riskStats.highCostProjects} 
                precision={0}
                valueStyle={{ color: riskStats.highCostProjects > 0 ? '#cf1322' : '#3f8600', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '150px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic 
                title="超工时项目" 
                value={riskStats.highHourProjects} 
                precision={0}
                valueStyle={{ color: riskStats.highHourProjects > 0 ? '#cf1322' : '#3f8600', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '150px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic 
                title="低回款项目" 
                value={riskStats.lowPaymentProjects} 
                precision={0}
                valueStyle={{ color: riskStats.lowPaymentProjects > 0 ? '#cf1322' : '#3f8600', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
        </div>
      </div>
      
      <div style={{ overflowX: 'auto', marginBottom: 24 }}>
        <div style={{ display: 'flex', minWidth: 'max-content' }}>
          <div style={{ minWidth: '150px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic 
                title="整包项目" 
                value={riskStats.projectTypeStats.fullPackage} 
                precision={0}
                valueStyle={{ fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '150px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic 
                title="人力项目" 
                value={riskStats.projectTypeStats.manpower} 
                precision={0}
                valueStyle={{ fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '150px' }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic 
                title="分包项目" 
                value={riskStats.projectTypeStats.subcontract} 
                precision={0}
                valueStyle={{ fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
        </div>
      </div>

      {/* 新增的筛选区域 */}
      <Card style={{ marginBottom: 24 }}>
        <Space size="large">
          <Checkbox 
            checked={filters.showOverdue}
            onChange={(e) => handleFilterChange({ showOverdue: e.target.checked })}
          >
            显示逾期项目 ({riskStats.overdueProjects})
          </Checkbox>
          <Checkbox 
            checked={filters.showHighCost}
            onChange={(e) => handleFilterChange({ showHighCost: e.target.checked })}
          >
            显示高成本项目 ({riskStats.highCostProjects})
          </Checkbox>
          <Checkbox 
            checked={filters.showHighHour}
            onChange={(e) => handleFilterChange({ showHighHour: e.target.checked })}
          >
            显示超工时项目 ({riskStats.highHourProjects})
          </Checkbox>
          <Checkbox 
            checked={filters.showLowPayment}
            onChange={(e) => handleFilterChange({ showLowPayment: e.target.checked })}
          >
            显示低回款项目 ({riskStats.lowPaymentProjects})
          </Checkbox>
          <Button 
            type="link" 
            onClick={() => setFilters({
              showOverdue: true,
              showHighCost: true,
              showHighHour: true,
              showLowPayment: true,
            })}
          >
            全选
          </Button>
          <Button 
            type="link" 
            onClick={() => setFilters({
              showOverdue: false,
              showHighCost: false,
              showHighHour: false,
              showLowPayment: false,
            })}
          >
            全不选
          </Button>
        </Space>
      </Card>
      
      <Table
        columns={columns}
        dataSource={getFilteredData()}
        rowKey="id"
        pagination={{ pageSize: 10 }}
        scroll={{ x: 2000 }}
        bordered
        size="middle"
      />
      
      <Modal
        title="合同内容"
        visible={contractVisible}
        onCancel={() => setContractVisible(false)}
        footer={null}
        width={800}
      >
        <div style={{ whiteSpace: 'pre-wrap', padding: '20px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
          {currentContract}
        </div>
      </Modal>
    </>
  );
};

// 辅助函数
const getStatusColor = (status) => {
  const colors = {
    '未验收': 'default',
    '验收中': 'blue',
    '开票中': 'orange',
    '待回款': 'purple',
    '已回款': 'green'
  };
  return colors[status] || 'default';
};

// 项目类型颜色
const getProjectTypeColor = (type) => {
  const colors = {
    '整包项目': 'magenta',
    '人力项目': 'volcano',
    '分包项目': 'gold'
  };
  return colors[type] || 'default';
};